<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\Common\Helpers\OpenOrderSignHelper;
use App\CustHub\Helpers\BcMath;
use App\CustHub\Interfaces\OpenWorkApplicationInterface;
use App\Setting\Service\SettingConfigService;
use Carbon\Carbon;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Stringable\Str;
use function Hyperf\Collection\collect;

class OpenOrderService
{
    #[Inject]
    protected SettingConfigService $configService;

    #[Inject]
    protected OpenWorkApplicationInterface $openWorkApplication;

    /**
     * @param string $corpId 企业ID
     * @param int $orderType 0=新购 1=扩容 2=续费
     * @param mixed $totalPrice 应用总价，单位分
     * @param int $userCount 应用的购买人数（要买多少席位、给多少用户开通使用权限）当购买类型是新购或扩容时需要填
     * @param int $durationDays 应用的购买时长，当购买类型是新购或续期时必填
     * @return array
     */
    public function paytoolOpenOrder(string $corpId,int $orderType,mixed $totalPrice,int $userCount = 0,int $durationDays = 0):array
    {
        $suiteId = $this->openWorkApplication->getOpenWork()->getAccount()->getSuiteId();

        $buy_info_list = [
            'suiteid' => $suiteId,
            'total_price' => BcMath::mul($totalPrice,100,0)
        ];

        if($durationDays > 0){
            $buy_info_list['duration_days'] = $durationDays;
        }

        if($userCount > 0){
            $buy_info_list['user_count'] = $userCount;
        }

        $data = [
            'business_type' => 2,
            'custom_corpid' => $corpId,
            'pay_type' => 2,//免支付
            'product_list' => [
                'customized_app' => [
                    'order_type' => $orderType,//0=新购 1=扩容 2=续费
                    'buy_info_list' => $buy_info_list
                ]
            ],
            'nonce_str' => Str::random(32),
            'ts' => time(),
        ];
        $sign = $this->getSign($data);
        $data['sig'] = $sign;

        $result = $this->openWorkApplication->paytoolOpenOrder($data);
        return $result;
    }

    public function getTodayOrderList($limit = 2000)
    {
        $startTime = Carbon::now()->subDay()->startOfDay()->timestamp;
        $endTime = Carbon::now()->subDay()->endOfDay()->timestamp;

        $cursor = '';
        $list = [];
        do{
            $data = [
                'business_type' => 2,
                'start_time' => $startTime,
                'end_time' => $endTime,
                'nonce_str' => Str::random(32),
                'limit' => $limit,
                'ts' => time()
            ];
            $data['cursor'] = $cursor;
            $sign = $this->getSign($data);
            $data['sig'] = $sign;
            $result = $this->openWorkApplication->paytoolGetOrderList($data);
            if($result['errcode'] !== 0){
                break;
            }
            $list = array_merge($list,$result['pay_order_list']);
            $cursor = $result['next_cursor'];
        }while(isset($result['has_more']) && $result['has_more'] == 1);

        return $list;
    }

    public function checkOrder(string $corpId): bool
    {
        $orderList = $this->getTodayOrderList();

        $orderCount = collect($orderList)->filter(function ($item) use ($corpId){
            return $item['custom_corpid'] == $corpId;
        })->count();

        return $orderCount >= 3;
    }

    private function getSign(array $data): string
    {
        // 获取收银台密钥
        $secret = $this->configService->getConfigByKey('syt_secret')['value'];

        $signHelper = new OpenOrderSignHelper($secret);

        return $signHelper->get($data);
    }
}